var argvType = process.argv[2]
var argvFile = process.argv[3]
var fs = require('fs')
var path = require('path')

var dirPath = path.join(__dirname, '/sysFile')

function createTime(ctimeMs) {
    var date1 = new Date(ctimeMs);
    var year = date1.getFullYear();
    var month = date1.getMonth() + 1;
    var day = date1.getDate();
    var hour = date1.getHours();
    var minute = date1.getMinutes();
    var minutes = minute < 10 ? '0' + minute : minute
    return year + '-' + month + '-' + day + ' ' + hour + ':' + minutes
}

function delDir(filePath) {
    if (fs.existsSync(filePath)) {
        var files = fs.readdirSync(filePath)
        for (var i = 0; i < files.length; i++) {
            var childPath = filePath+ '/' + files[i]
            var fileObj = fs.statSync(childPath);
            if (fileObj.isFile()) {
                fs.unlinkSync(childPath);
            }
            else if (fileObj.isDirectory()) {
                delDir(childPath)
            }
        }
        fs.rmdirSync(filePath)
    }
    else {
        console.log('文件路径不存在')
    }
}



if (argvType == '-list') {
    var files = fs.readdirSync(dirPath)
    var arr = []

    for (var i = 0; i < files.length; i++) {
        var fileObj = fs.statSync(dirPath + '/' + files[i])
        if (fileObj.isFile()) {
            var obj = {}
            obj.fileName = files[i]
            obj.fileSize = fileObj.size
            obj.createTime = createTime(fileObj.ctimeMs)
        }
        else if (fileObj.isDirectory()) {
            var obj = {}
            obj.fileName = files[i]
            obj.fileSize = fileObj.size
            obj.createTime = createTime(fileObj.ctimeMs)
        }
        arr.push(obj)
    }

    arr.sort(function (a, b) {
        return a.createTime > b.createTime ? 1 : -1;
    })

    console.log(JSON.stringify(arr))


}
else if (argvType == '-show') {
    var path = path.join(__dirname, '/sysFile/' + argvFile)
    if (fs.existsSync(path)) {
        fs.readFile(path, (err, data) => {
            if (err) {
                console.log(err)
            } else {
                console.log(data.toString('utf-8'))
            }
        })
    } else {
        console.log('该文件不存在')
    }

}
else if (argvType == '-del') {
    var path = path.join(__dirname, '/sysFile/' + argvFile)
    var fileObj = fs.statSync(path)
    if (fileObj.isFile()) {
        fs.unlinkSync(path) 
    }
    else if (fileObj.isDirectory()) {
        delDir(path)
        
    }
    console.log(argvFile+'删除成功')
}